package com.juntuo.controller;


import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebClientOptions;
import com.gargoylesoftware.htmlunit.html.*;
import com.juntuo.Enums.CertStatus;
import com.juntuo.util.CertificateUtils;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.xmlbeans.SchemaLocalAttribute;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;

public class Test {
    public static void main(String[] args) throws Exception {


//        trustEveryone();
//        Protocol easyhttps = new Protocol("https", new
//                EasySSLProtocolSocketFactory(), 443);
//        Protocol.registerProtocol("https", easyhttps);

        final WebClient webClient = new WebClient(BrowserVersion.CHROME);//新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
//        webClient.getOptions().setUseInsecureSSL(true);
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        webClient.getOptions().setJavaScriptEnabled(false); //很重要，启用JS
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
//        webClient.waitForBackgroundJavaScript(1800000);//异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束
        HtmlPage page = null;
        try {
            String url = "https://content.infomantis.de/impf/?app=dekra-certifiedProducts&PHPSESSID=&view=form&search=certificateNumber";
            page = webClient.getPage(url);
//            webClient.waitForBackgroundJavaScript(180000);//异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束
            HtmlInput firstname=(HtmlInput)page.getElementById("firstname");
            firstname.setValueAttribute("qqq");
            HtmlInput lastname=page.querySelector("#lastname");
            lastname.setValueAttribute("qqq");
            HtmlInput phone=page.querySelector("#phone");
            phone.setValueAttribute("133456788");
            HtmlInput email=page.querySelector("#email");
            email.setValueAttribute("3313971898@qq.com");
            HtmlTextArea reason=page.querySelector("#reason");
            reason.setText("check valid");
            HtmlInput cert=page.querySelector("#subForm-certificatenumber");
            cert.setValueAttribute("31-1017681");


            HtmlSubmitInput button = page.querySelector("#search");
            HtmlPage nextPage = button.click();
            String result = nextPage.asXml();

            if(result.contains("matched no certificates")){
                System.out.println("00000000000");
            }
            if(result.contains("You will be")){
                System.out.println("111111");
            }
                System.out.println(CertStatus.NEED_CHANGE_LOGIC.getCode());
//                return CertStatus.NEED_CHANGE_LOGIC.getCode();
                    System.out.println(CertStatus.OK.getCode());
//                    return CertStatus.OK.getCode();
                    System.out.println(CertStatus.NEED_CHANGE_LOGIC.getCode());
//                return CertStatus.NEED_CHANGE_LOGIC.getCode();



        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            webClient.close();
        }

//        webClient.waitForBackgroundJavaScript(30000);//异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束
//
//        String pageXml = page.asXml();//直接将加载完成的页面转换成xml格式的字符串

//        TODO 下面的代码就是对字符串的操作了,常规的爬虫操作,用到了比较好用的Jsoup库
//
//        Document document = Jsoup.parse(pageXml);//获取html文档
//
//
//
//
//        //获取指定网址的页面内容
//        System.out.println(document);
//        Elements elements=document.getElementsByClass("zertreg-search-txtinput");
//        Element element = elements.get(0);
//        element.val("40022721");
//
//            Elements btns=document.select("[type=submit].zertreg-search-btnsearch");
//            System.out.println(btns);



    }

    /**
     * 信任任何站点，实现https页面的正常访问
     *
     */

    public static void trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            // e.printStackTrace();
        }
    }

}
